package com.quktzhuanka.app.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.quktzhuanka.app.R;
import com.quktzhuanka.app.adapter.MyOrderDetailAdapter;
import com.quktzhuanka.app.base.BaseActivity;
import com.quktzhuanka.app.bean.OrderDetailBean;
import com.quktzhuanka.app.bean.OrderDetailBean2;
import com.quktzhuanka.app.bean.Response;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.https.onOKJsonHttpResponseHandler;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
import me.drakeet.materialdialog.MaterialDialog;

public class ShopMallOrderDetailActivity extends BaseActivity {
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.txt_status)
    TextView txtStatus;
    @BindView(R.id.txt_cancle)
    TextView txtCancle;
    @BindView(R.id.txt_wuliu)
    TextView txtWuLiu;
    @BindView(R.id.txt_apply_cancle)
    TextView txtApplyCancle;
    @BindView(R.id.txt_danhao)
    TextView txtDanhao;
    @BindView(R.id.txt_pay)
    TextView txtPay;
    @BindView(R.id.txt_ok_shouhuo)
    TextView txtOkShouhuo;
    @BindView(R.id.txt_comment)
    TextView txtComment;
    @BindView(R.id.order_recy)
    RecyclerView orderRecy;
    @BindView(R.id.txt_price)
    TextView txtPrice;
    @BindView(R.id.txt_total_price)
    TextView txtTotalPrice;
    @BindView(R.id.txt_delivery_type)
    TextView txtDeliveryType;
    @BindView(R.id.txt_remark)
    TextView txtRemark;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.txt_order_num)
    TextView txtOrderNum;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.txt_reason)
    TextView txtReason;
    @BindView(R.id.txt_pay_time)
    TextView txtPayTime;
    @BindView(R.id.txt_use_point)
    TextView txtUsePoint;
    @BindView(R.id.txt_back_point)
    TextView txtBackPoint;
    private OrderDetailBean orderDetailBean;
    private MyOrderDetailAdapter adapter;
    private List<OrderDetailBean.OrderDetail2> list = new ArrayList<>();
    private MaterialDialog materialDialog;

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_orderdetail);
        ButterKnife.bind(this);
        tvLeft.setVisibility(View.VISIBLE);
        tvTitle.setText("订单详情");
        orderDetailBean = (OrderDetailBean) getIntent().getExtras().get("order");
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        orderRecy.setLayoutManager(layoutManager);
        orderRecy.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter = new MyOrderDetailAdapter(this, R.layout.item_order_detail, list);
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("goods_id", list.get(position).goods_id);
                openActivity(MallGoodsDetailsActivity.class, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        orderRecy.setAdapter(adapter);
        materialDialog = new MaterialDialog(this);
        getDetail();
    }

    @Override
    protected void initData() {
        switch (orderDetailBean.status) {
            case "1":
                txtStatus.setText("待支付");
                txtPay.setVisibility(View.VISIBLE);
                txtCancle.setVisibility(View.VISIBLE);
                break;
            case "2":
                txtStatus.setText("待发货");
                txtApplyCancle.setVisibility(View.VISIBLE);
                break;
            case "3":
                txtStatus.setText("待收货");
                txtOkShouhuo.setVisibility(View.VISIBLE);
                txtWuLiu.setVisibility(View.VISIBLE);
                txtApplyCancle.setVisibility(View.VISIBLE);
                break;
            case "4":
                txtStatus.setText("订单已签收");
                txtComment.setVisibility(View.VISIBLE);
                break;
            case "5":
                txtStatus.setText("已完成");
                break;
            case "6":
                txtStatus.setText("申请退款中...");
                txtReason.setText("退款原因: " + orderDetailBean.drawback_reason);
                txtReason.setVisibility(View.VISIBLE);
                break;
            case "7":
                if(orderDetailBean.refund_express_number!=null&&!"".equals(orderDetailBean.refund_express_number)){
                    txtStatus.setText("退货中，待退款...");
                }else{
                    txtStatus.setText("待退货...");
                    txtDanhao.setVisibility(View.VISIBLE);
                }
                break;
            case "8":
                txtStatus.setText("拒绝退款");
                txtApplyCancle.setVisibility(View.VISIBLE);
                txtReason.setText("拒绝原因: " + orderDetailBean.drawback_refuse_reason);
                txtReason.setVisibility(View.VISIBLE);
//                Drawable drawable1 = getResources().getDrawable(R.mipmap.order_cancle);
//                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
//                txtStatus.setCompoundDrawables(null, drawable1, null, null);
                break;
            case "9":
                txtStatus.setText("已退款");
                break;
        }
        txtCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDialog.setTitle("取消订单")
                        .setMessage("确定取消该条订单吗")
                        .setNegativeButton("立即取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                requestCancle();
                                materialDialog.dismiss();
                            }
                        }).setPositiveButton("再想想", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        materialDialog.dismiss();
                    }
                }).setCanceledOnTouchOutside(true)
                        .show();
            }
        });
        txtPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ShopMallOrderDetailActivity.this, PayOrderMoneyActivity.class);
                intent.putExtra("money", ""+(Double.valueOf(orderDetailBean.detail.get(0).allprice) - Integer.valueOf(orderDetailBean.deduction_point == null ? "0" : orderDetailBean.deduction_point)));
                intent.putExtra("order_num", orderDetailBean.id);
                intent.putExtra("order_num1", orderDetailBean.order_num);
                startActivity(intent);
            }
        });
        txtWuLiu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(ShopMallOrderDetailActivity.this,ExpressActivity.class);
                intent.putExtra("number",orderDetailBean.express_number);
                intent.putExtra("logistics",orderDetailBean.logistics);
                startActivity(intent);
            }
        });
        txtApplyCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("order_num", orderDetailBean.order_num);
                bundle.putString("order_detail_id", orderDetailBean.id);
                Intent intent = new Intent(ShopMallOrderDetailActivity.this, ApplyDrawBackActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        txtOkShouhuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                materialDialog.setTitle("确认收货")
                        .setMessage("确认已收到商品吗?")
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                materialDialog.dismiss();
                            }
                        }).setPositiveButton("确认收货", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        okShouHuo();
                        materialDialog.dismiss();
                    }
                }).setCanceledOnTouchOutside(true)
                        .show();
            }
        });
        txtTime.setText(orderDetailBean.createtime);
        txtOrderNum.setText(orderDetailBean.order_num);
        txtPayTime.setText(orderDetailBean.pay_time);
    }

    private void okShouHuo() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("order_id", orderDetailBean.id);
        HttpUtils.post(Constants.CONFIRM_ORDER, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    String msg = jsonObject.optString("msg");
                    if (jsonObject.getInt("code") == 0) {
                        showToast("收货成功");
                        txtStatus.setText("已收货");
                        txtApplyCancle.setVisibility(View.VISIBLE);
                        txtComment.setVisibility(View.VISIBLE);
                        txtOkShouhuo.setVisibility(View.GONE);
                    } else {
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void requestCancle() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("order_id", orderDetailBean.id);
        HttpUtils.post(Constants.CANCLE_MALL_ORDER, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    String msg = jsonObject.optString("msg");
                    if (jsonObject.getInt("code") == 0) {
                        showToast("取消成功");
                        finish();
                    } else {
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getDetail() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("order_id", orderDetailBean.id);
//        requestParams.put("order_detail_id", orderDetailBean.order_detail_id);
        HttpUtils.post(Constants.GET_ORDER_DETAIL, requestParams, new onOKJsonHttpResponseHandler<OrderDetailBean2>(new TypeToken<Response<OrderDetailBean2>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, final Response<OrderDetailBean2> datas) {
                if (datas.isSuccess()) {
                    list.addAll(datas.getData().orderMsg.detail);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            txtRemark.setText(datas.getData().orderMsg.remark);
                            txtBackPoint.setText(orderDetailBean.detail.get(0).all_give_point);
                            txtUsePoint.setText(orderDetailBean.deduction_point==null?"0":orderDetailBean.deduction_point);
                            txtTotalPrice.setText("￥" + (Double.valueOf(orderDetailBean.detail.get(0).allprice) - Double.valueOf(orderDetailBean.deduction_point == null ? "0" : orderDetailBean.deduction_point)));
                            txtPrice.setText("￥" + datas.getData().orderMsg.detail.get(0).allprice);
                            txtDeliveryType.setText("包邮");
                            txtAddress.setText(Html.fromHtml(datas.getData().orderMsg.consignee + "&nbsp;" + datas.getData().orderMsg.contact_number + "<br/><font size='12px'color='#999999'>" + datas.getData().orderMsg.address + "</font>"));
                            adapter.notifyDataSetChanged();
                        }
                    });
                } else {
                    showToast(datas.getMsg());
                }
            }
        });
    }

    @Override
    protected void initListener() {

    }

    @OnClick({R.id.tv_left, R.id.txt_cancle, R.id.txt_apply_cancle, R.id.txt_pay, R.id.txt_ok_shouhuo, R.id.txt_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.txt_cancle:
                break;
            case R.id.txt_apply_cancle:
                break;
            case R.id.txt_pay:
                break;
            case R.id.txt_ok_shouhuo:
                break;
            case R.id.txt_comment:
                break;
        }
    }
}
